#!/usr/bin/python
import subprocess
from matplotlib import pyplot as plt
from matplotlib import patches

FILE = lambda n: "files/{}.txt".format(n)
CMD = "java TfIdfViewer {} {}"
NOVELS = ('DarwinOriginofSpecies',
          'DickensAChristmasCarol',
          'DickensGreatExpectations',
          'DickensThePickwickPapers',
          'KiplingJungleBook',
          'LondonCallofTheWild',
          'PoeWorksVol1',
          'PoeWorksVol2',
          'RiceBurroughsAprincessofMars',
          'WellsTimeMachine',
          'WellsWarofTheWorlds')
N = len(NOVELS)

results = []
same = []
diff = []
for r1, n1 in enumerate(NOVELS):
    f1 = FILE(n1)
    for r2, n2 in enumerate(NOVELS):
        f2 = FILE(n2)
        num = float(subprocess.check_output(CMD.format(f1, f2), shell=True))
        author = n1[:2] == n2[:2]
        results.append((r1, r2, num, author))
        if n1 < n2:
            same.append(num) if author else diff.append(num)
        print("{} {} {}".format(f1, f2, num))

x, y, size, author = zip(*results)

print('mateix:   {}'.format(sum(same) / len(same)))
print('diferent: {}'.format(sum(diff) / len(diff)))

ax = plt.figure().add_subplot(111, aspect='equal')
for i in range(len(results)):
    xy = (x[i], y[i])
    if x[i] == y[i]:
        c = (0, 0, 0)
    elif author[i]:
        c = (0.1, 0.3, 0.7)
    else:
        c = (0.8, 0.2, 0.2)
    s = size[i] / 2.5
    ax.add_patch(patches.Circle(xy=xy, radius=s, facecolor=c, linewidth=0))

plt.axis([-1, N, -1, N])
NOVELS = [n[:11] + '...' if len(n) > 15 else n for n in NOVELS]
a, b = plt.yticks(range(N), NOVELS)
a, b = plt.xticks(range(N), NOVELS)
plt.setp(b, 'rotation', 'vertical')
plt.savefig("compare_novels_plot.png", bbox_inches='tight')
